//
//  KINGHomeTableViewController.swift
//  肉荣微博
//
//  Created by king on 15/7/28.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

/// 定义cell类型枚举，并定义函数返回cell重用id
private enum StatusCellIdentifier:String {
    case Normal = "KINGStatusNormalCell"
    case Forward = "KINGStatusForwardCell"
    //静态函数，用于枚举直接调用
    static func cellID(states:KINGStatuses) -> String {
        return states.retweeted_status == nil ? StatusCellIdentifier.Normal.rawValue : StatusCellIdentifier.Forward.rawValue
//        return StatusCellIdentifier.Forward.rawValue
    }
}


class KINGHomeTableViewController: KINGBaseTableViewController {
    
    private var statuses : [KINGStatuses]? {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if KINGUserAccount.isLogin {
            return
        }
        tabBarItem.badgeValue = "猪肉荣"
        prepareTableView()
        loadData()
        //注册通知，获取cell对图片的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: KINGStatusCellSelectPictureNotification, object: nil)
    }
    private var pictureView:KINGPictureView?
    private var currentIndexPath:NSIndexPath?
    //MARK: - 通知处理函数
    func selectPicture(n:NSNotification) {
        //收到通知之后，一定要对数据进行检查，否则会造成程序崩溃
        guard let indexPath = n.userInfo![KINGStatusCellSelectPictureIndexPathKey] as? NSIndexPath else {
            return
        }
        guard let urls = n.userInfo![KINGStatusCellSelectPictureURLKey] as? [NSURL] else {
            return
        }
        //print(n.userInfo![KINGStatusCellSelectPictureURLKey])
        guard let obj = n.object as? KINGPictureView else {
            return
        }
        //记录pictureView & indexPath
        pictureView = obj
        currentIndexPath = indexPath
        //给替代执行动画控件赋值
        iconImageView.sd_setImageWithURL(urls[indexPath.item])
        
        let pbc = KINGPhotoBrowserController(urls: urls, index: indexPath.item)
        //专场动画准备, 设置谁来准备转场动画
        pbc.transitioningDelegate = self
        //设置转场的样式为自定义
        pbc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(pbc, animated: true, completion: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func prepareTableView() {
        /// 注册的时候，一定记住要加上rawValue,否则类型不匹配，如果不加上就是个枚举，
        tableView.registerClass(KINGStatusNormalCell.self, forCellReuseIdentifier: StatusCellIdentifier.Normal.rawValue)
        tableView.registerClass(KINGStatusForwardCell.self, forCellReuseIdentifier: StatusCellIdentifier.Forward.rawValue)
        tableView.estimatedRowHeight = 290
        //        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        //        tableView.rowHeight = 150
        //MARK: - 下来刷新控件
        refreshControl = KINGRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        prepareTipView()
    }
    //准备提示视图，将其添加到navigationBar上，最底层
    func prepareTipView() {
        let h:CGFloat = 44.0
        tipView.frame = CGRect(origin: CGPointMake(0, -2*h), size: CGSize(width: view.bounds.width, height: h))
        navigationController?.navigationBar.insertSubview(tipView, atIndex: 0)
    }
    //显示刷新按钮
    private func showTipView(count:Int) {
//        let h:CGFloat = 44.0
//        let tipView = UILabel(frame: CGRect(origin: CGPointMake(0, -2*h), size: CGSize(width: view.bounds.width, height: h)))
//        tipView.textAlignment = NSTextAlignment.Center
//        tipView.backgroundColor = UIColor.orangeColor()
//        navigationController?.navigationBar.insertSubview(tipView, atIndex: 0)
        //解决连续下拉刷新，tipView跑到下面的问题
        if tipView.layer.animationForKey("position") != nil {
            print("动画正在执行")
            return
        }
        let text = (count == 0) ? "没有更多微博" : "刷新了\(count)微博"
        tipView.text = text
        let rect = tipView.frame
        UIView.animateWithDuration(1.5, animations: { () -> Void in
            self.tipView.frame = CGRectOffset(self.tipView.frame, 0, 3 * rect.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.5, animations: { () -> Void in
                    self.tipView.frame = rect
                })
        }
    }
    //刷新标识开关、当下拉刷新的时候，被置为true
    private var pullupRefreshFlage = false
    
    func loadData() {
        //MARK: - 这里有循环应用
        refreshControl?.beginRefreshing()
        var since_id: Int = statuses?.first?.id ?? 0
        var max_id: Int = 0
        if pullupRefreshFlage {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
            pullupRefreshFlage = false
        }
        KINGStatuses.loadData(since_id, max_id:max_id) { (dataList, error) -> () in
            self.refreshControl?.endRefreshing()
            if error != nil {
                print(error)
                return
            }
            let count = dataList!.count
            if since_id > 0 {
                self.showTipView(count)
            }
            print("刷新了\(count)条数据")
            //对不同的效果进行处理
            if since_id > 0 {//如果是上啦刷新，将数据添加到前面
                self.statuses = dataList! + self.statuses!
                //self.statuses = dataList
            } else if max_id > 0 {//如果是下来刷新，就将数据添加都后面
                self.statuses! += dataList!
            } else {//否则 直接复制
                self.statuses = dataList
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        /// 利用枚举获取不同类型的cell，转发微博或是平常的微博
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(statuses![indexPath.row]), forIndexPath: indexPath) as! KINGStatusCell
        
        cell.status = statuses![indexPath.row]
        //如果是最后一个数据，就进行下来刷新
        if indexPath.row == statuses!.count - 1 {
            //设置标记，作为下拉刷新的开关
            pullupRefreshFlage = true
            loadData()
        }
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //如果本cell 已经缓存数据，直接返回
        let status = statuses![indexPath.row]
        if let height = status.rowHeight {
            return height
        }
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status)) as! KINGStatusCell
        status.rowHeight = cell.heightForCell(status)
        return status.rowHeight!
    }
    //MARK: - 懒加载提示控件
    private lazy var tipView:UILabel = {
        let label = UILabel()
        label.textAlignment = NSTextAlignment.Center
        label.backgroundColor = UIColor.orangeColor()
        return label
    }()
    //懒加载代替执行动画的imageView
    private lazy var iconImageView:UIImageView = {
        let view = UIImageView()
        //设置图片缩放模式
        view.contentMode = UIViewContentMode.ScaleAspectFill
        view.clipsToBounds = true
        return view
    }()
    private lazy var isPresented = false
}
//MARK: - UIViewControllerTransitioningDelegate
extension KINGHomeTableViewController: UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

extension KINGHomeTableViewController:UIViewControllerAnimatedTransitioning{
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2
    }
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        if isPresented {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            let smallFrame = pictureView!.cellForScreenFrame(currentIndexPath!)
            let bigFrame = pictureView!.cellForFullScreenFrame(currentIndexPath!)
            
            transitionContext.containerView()?.addSubview(iconImageView)
            transitionContext.containerView()?.addSubview(toView)
            iconImageView.frame = smallFrame
            toView.alpha = 0.0
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                    self.iconImageView.frame = bigFrame
                    toView.alpha = 1.0
                }) { (_) -> Void in
                    self.iconImageView.removeFromSuperview()
                    //transitionContext.containerView()?.addSubview(toView)
                transitionContext.completeTransition(true);
            }
        } else {//表示是消除动画，fromVC KINGPhotoBrowserController， fromView：view
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! KINGPhotoBrowserController
            let curIndexPath = fromVC.currentImageIndex()
            let rect = pictureView!.cellForScreenFrame(curIndexPath)
            //获取当前正在显示的imageView，并添加到容器视图中
            let iv = fromVC.currentImageView()
            transitionContext.containerView()?.addSubview(iv)
            //设置图像视图的中心位置，如果不设置，图像会跳动，因为iv的位置是在scroll上的位置
            iv.center = fromView!.center
            //累加父视图的形变，因为只有view在做形变，imageView并没有变化，所以会造成松手的瞬间，图像变大之后在回去
            let scale = fromView!.transform.a
            iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
            //将view从父视图中移除
            fromView?.removeFromSuperview()
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//                fromView?.alpha = 0.0
                //对iv做动画
                iv.frame = rect
                }, completion: { (_) -> Void in
                    iv.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
}
